package com.zghhost.codedemo.concurrent.thread;

import java.util.concurrent.*;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/1/11 16:56
 */
public class ThreadTest {


    public static void main(String[] args){
        ExecutorService es = Executors.newFixedThreadPool(100);

        LinkedBlockingQueue<String> q = new LinkedBlockingQueue<String>();
        try{
            /**
             * 执行完需要耗时  1s - 创建时间总和
             */
            long sts = System.currentTimeMillis();
            int n = 100000;
            for (int i = 0; i < n; i++) {
                q.add("");
                es.execute(new TestThread(q));
            }
            long ets = System.currentTimeMillis();
            System.out.println("创建"+n+"个线程耗时："+(ets-sts)+" 毫秒");


            new Thread(){
                @Override
                public void run() {
                    while (q.size() > 0){
                    }
                    long tets = System.currentTimeMillis();
                    System.out.println("所有线程执行完消耗："+(tets - sts)+" 毫秒");
                }
            }.start();
        }catch (OutOfMemoryError e){
            System.out.println("内存溢出了，当前线程数量"+q.size());
            e.printStackTrace();
        }

    }

    /**
     * 一个工作完需要耗时一秒的线程
     */
    static class TestThread extends Thread{
        LinkedBlockingQueue<String> q;

        TestThread(LinkedBlockingQueue<String> q){
            this.q = q;
        }

        @Override
        public void run() {
            try{
                sleep(5);
                q.poll();
            }catch (Exception e){}
        }
    }
}
